<template>
	<view class="login">
		<view class="title">用户登陆</view>
		<view class="login-item">
			<input type="text" placeholder="请输入手机号" v-model="tel" />
		</view>
		<view class="login-item">
			<input type="text" placeholder="请输入验证码" v-model="code" />
			<button :disabled="time !== downTime" type="primary" class="code" size="mini" @click="curtDown">
				{{ time === downTime ? '获取验证码' : `还剩${downTime}秒结束` }}
			</button>
		</view>

		<button type="primary" @click="handleLogin">登陆</button>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	const tel = ref('13111111111')
	const code = ref('')
	const systemCode = ref('')
	const time = ref(60);
	const downTime = ref(time.value)
	const handleLogin = async () => {
		if(code.value !== systemCode.value) {
			uni.showToast({
				title: '验证码不正确'
			})
			return 
		}
		const resp = await uniCloud.callFunction({
			name: 'getUserInfoByTel',
			data: {
				tel: tel.value
			}
		})
		const data = resp.result.data
		if(data.length) {
			const userInfo = data[0];
			uni.setStorageSync('userInfo', userInfo);
			uni.switchTab({
				url: '/pages/my/my'
			})
		} else {
			uni.showToast({
				title: '手机号未注册',
				icon: 'error'
			})
		}
		
	}
	const curtDown = async () => {
		// 1. 验证手机号
		const reg = /^1[3-9]\d{9}$/g;
		if(!reg.test(tel.value)) {
			uni.showToast({
				title: '手机号格式不正确',
				icon: 'error'
			})
			return ;
		}
		
		// 2. 倒计时
		downTime.value--
		const timer = setInterval(() => {
			downTime.value--;
			if(downTime.value <= 0) {
				clearInterval(timer);
				downTime.value = time.value
			}
		}, 1000)
		
		
		// 3. 获取验证码
		const resp = await uniCloud.callFunction({
			name: 'getTelCode'
		})
		console.log(resp.result)
		systemCode.value = resp.result
		
	}
</script>

<style lang="scss" scoped>
	.login {
		padding: 20px;

		.title {
			font-size: 30px;
			text-align: center;
			font-weight: bold;
		}

		.login-item {
			display: flex;
			height: 60px;
			align-items: center;

			.code {
				height: 40px;
				line-height: 40px;
				width: 120px;
			}

			input {
				flex: 1;
				border: 1px solid #ccc;
				border-radius: 10px;
				height: 40px;
			}
		}
	}
</style>